package io.itit.ecp.admin.provide.action.controller.miniprogram;


import com.alibaba.fastjson.JSON;
import io.itit.ecp.admin.provide.action.resp.CommonLoginTokenResp;
import io.itit.ecp.admin.provide.action.resp.CommonLoginUserInfoResp;
import io.itit.ecp.admin.provide.utils.HttpClientUtil;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.web.wall.action.req.LoginReq;
import io.itit.grass.web.wall.action.resp.LoginResp;
import io.itit.grass.web.wall.helper.ShiroUserHelper;
import io.itit.grass.web.wall.model.JwtToken;
import io.itit.grass.web.wall.utils.ShiroUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登陆接口
 */
@Slf4j
@Api(tags = "统一登录")
@RestController
@RequestMapping("/mini/login")
public class MiniLoginController {

    @Value("${mini.loginUrl:http://192.168.1.117/agcim-auth/login}")
    private String loginUrl;

    @Value("${cimLogin.getUserInfoUrl}")
    private String getUserInfoUrl;

    /**
     * 小程序 统一登陆
     */
    @PostMapping("/")
    public ResultResp<?> login(@RequestBody @Validated LoginReq req) {
        String code = getCode(req);
        String loginUrl = this.loginUrl + "?code=" + code;
        String response = HttpClientUtil.sendPost(loginUrl, "");
        log.info("response:{}", response);
        CommonLoginTokenResp tokenResp = JSON.parseObject(response, CommonLoginTokenResp.class);
        Map<String, String> headers = new HashMap<>();
        headers.put(HttpHeaders.AUTHORIZATION, "Bearer  " + tokenResp.getAccess_token());
        String userInfoRes = HttpClientUtil.sendPost(getUserInfoUrl, null, headers);
        CommonLoginUserInfoResp userInfoResp = JSON.parseObject(userInfoRes, CommonLoginUserInfoResp.class);
        CommonLoginUserInfoResp.Content content = userInfoResp.getContent();
        CommonLoginUserInfoResp.User user = content.getUser();
        JwtToken jwtToken = new JwtToken(user.getUserId());
        jwtToken.setUsername(user.getUserName());
        ShiroUtils.getSubject().login(jwtToken);
        String token = ShiroUserHelper.i().setJwtToken();
        LoginResp resp = new LoginResp();
        resp.setUserName(req.getUserName());
        resp.setFullName(user.getUserName());
        resp.setLoginTm(new Date());
        resp.setToken(token);
        return ResultResp.success();
    }

    private String getCode(LoginReq req) {
        Map<String, Object> body = new HashMap<>();
        body.put("loginName", req.getUserName());
        body.put("phone", req.getUserName());
        body.put("pwd", req.getPassword());
        body.put("timestamp", System.currentTimeMillis() / 1000);
        return Base64.encodeBase64String(JSON.toJSONString(body).getBytes(StandardCharsets.UTF_8));
    }
}
